<?php
#### CALL ######################################################################
function call($method, $slice = false) {
	if (!method_exists(base()->object, $method)) return false;
	if (!$slice) $slice = (is_numeric(cleanMethodName(url(2))) ? 2 : 3);
	$params = array_slice(urlArray(true), $slice);

	call_user_func_array(array(base()->object, $method), $params);
	return true;
}

#### CALL METHOD ###############################################################
function callMethod($name = false, $default = 'index') {
	if (!$name) $name = (is_numeric(cleanMethodName(url(2))) ? url(3) : url(2));
	$name = cleanMethodName($name);
	if (!call($name)) call($default);
}

#### CALL REST #################################################################
function callREST() {

	// Remove hidden form element
	if (isset($_POST['_method'])) {
		$_SERVER['REQUEST_METHOD'] = strtoupper($_POST['_method']);
		unset($_POST['_method']);
	}

	switch ($_SERVER['REQUEST_METHOD']) {
		case 'GET':
			// Only call on exact URL e.g example.com/news/1 and not 
			// example.com/news or example.com/news/1/edit
			if (!url(3) && is_numeric(cleanMethodName(url(2)))) {
				return call('get', 2);
			}
			break;
		case 'POST':
			return call('post', 2);
			break;		
		case 'PUT':
			return call('put', 2);
			break;
		case 'DELETE':
			return call('delete', 2);
			break;
	}
}

#### CLEAN METHOD NAME #########################################################
function cleanMethodName($name) {
	$name = strtolower($name);
	$name = str_replace('-', '', $name);
	$name = str_replace('_', '', $name);
	return $name;
}
?>